package com.dbapp.garden.controller.contract;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.dbapp.garden.config.security.PermissionUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.entity.GardenContractTemplet;
import com.dbapp.garden.entity.GardenSmallTicketInfo;
import com.dbapp.garden.service.IGardenContractTempletService;
import com.dbapp.garden.service.IGardenSmallTicketInfoService;

@Controller
public class ContractTempletController extends BaseContractController {

    @Autowired
    IGardenContractTempletService templetService;

    @GetMapping("/contracttempletinfo")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CONTRACT_TEMPLATE') or hasAuthority('PERMISSION_CONTRACT_TEMPLATE_VIEW')")
    public Map<String, ?> detailContractTemplet(@SessionAttribute("user") PermissionUser user) {

        GardenContractTemplet templetInfo = templetService.findByGardenId(user.getGardenId());
        return RenderJSON.makeStandMap(1, "获取成功！", templetInfo);
    }

    @PostMapping("/contracttempletedit")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CONTRACT_TEMPLATE_EDIT')")
    public Map<String, ?> editContractTemplet(@SessionAttribute("user") PermissionUser user, @RequestBody @Valid GardenContractTemplet templetInfo) {
        if (templetInfo == null) {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }

        if (StringUtils.isBlank(templetInfo.getContractTemplet())) {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！合同模板为空", "error");
        }

        if (templetInfo.getId() != null) {
            GardenContractTemplet tInfo = templetService.findById(templetInfo.getId());
            if (tInfo == null) {
                return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
            }
            if (!tInfo.getGarden_id().equals(user.getGardenId())) {
                return RenderJSON.makeStandMap(1, "对不起，您没有权限，编辑失败！", "error");
            }
        }
        templetInfo.setUpdateDate(new Date());
        templetInfo.setGarden_id(user.getGardenId());
        templetInfo = templetService.saveTemplet(templetInfo);
        if (templetInfo != null) {
            return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }

    }
}
